// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package gender

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/errs"
	"server/app/http/models"
	"server/app/http/services"
	"server/app/lib/authorizer"
)

type Logic struct {
	auth     *authorizer.Authentication
	request  *Request
	response *Response
}

func New() logics.Logical {
	return &Logic{
		request:  &Request{},
		response: &Response{},
	}
}

func (o *Logic) Before(_ context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.auth = authorizer.New().Get(i)
	}
	return
}

func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		err     error
		res     = result.New()
		service = services.NewUsersService()
	)

	if _, err = service.UpdateGender(ctx, &models.Users{
		Id:     o.auth.UserId,
		Gender: o.request.Gender,
	}); err != nil {
		res.WithError(errs.ErrDatabaseQuery)
		return res
	}

	o.response.Gender = o.request.Gender
	o.response.GenderText = o.request.Gender.Text()
	return res.With(o.response)
}
